import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../providers/todo_provider.dart';
import '../../../domain/entities/todo.dart';
import '../../../domain/entities/project.dart' show Priority;
import '../../widgets/platform/adaptive_card.dart';
import '../../widgets/platform/responsive_layout.dart';
// 导入窗口管理器
import '../../../core/platform/window_manager.dart';

/// 待办任务列表页面
class TodoListPage extends ConsumerStatefulWidget {
  const TodoListPage({super.key});

  @override
  ConsumerState<TodoListPage> createState() => _TodoListPageState();
}

class _TodoListPageState extends ConsumerState<TodoListPage>
    with TickerProviderStateMixin {
  late TabController _tabController;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 4, vsync: this);

    // 加载待办任务列表
    WidgetsBinding.instance.addPostFrameCallback((_) {
      ref.read(todoStateProvider.notifier).loadTodos();
    });

    // 设置窗口为可调整大小
    _setResizableWindow();
  }

  // 设置窗口为可调整大小
  void _setResizableWindow() {
    WindowManager.setWindowStyle(false); // 可调整大小
    // 设置窗口为笔记本大小
    WindowManager.setWindowSize(1200, 800); // 设置窗口大小为更大的笔记本大小
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final todoState = ref.watch(todoStateProvider);
    final todosByStatus = ref.watch(todosByStatusProvider);

    return Scaffold(
      appBar: AppBar(
        title: const SelectableText('我的待办'),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => Navigator.of(context).pop(),
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: () {
              ref.read(todoStateProvider.notifier).loadTodos();
            },
          ),
          IconButton(
            icon: const Icon(Icons.add),
            onPressed: () {
              _showCreateTodoDialog(context);
            },
          ),
        ],
        bottom: TabBar(
          controller: _tabController,
          tabs: [
            Tab(
              child: _buildTabWithBadge(
                '待办',
                todosByStatus[TodoStatus.todo]?.length ?? 0,
              ),
            ),
            Tab(
              child: _buildTabWithBadge(
                '进行中',
                todosByStatus[TodoStatus.inProgress]?.length ?? 0,
              ),
            ),
            Tab(
              child: _buildTabWithBadge(
                '已完成',
                todosByStatus[TodoStatus.done]?.length ?? 0,
              ),
            ),
            Tab(
              child: _buildTabWithBadge(
                '已阻塞',
                todosByStatus[TodoStatus.blocked]?.length ?? 0,
              ),
            ),
          ],
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        children: [
          _buildTodoList(todoState, todosByStatus[TodoStatus.todo] ?? []),
          _buildTodoList(todoState, todosByStatus[TodoStatus.inProgress] ?? []),
          _buildTodoList(todoState, todosByStatus[TodoStatus.done] ?? []),
          _buildTodoList(todoState, todosByStatus[TodoStatus.blocked] ?? []),
        ],
      ),
    );
  }

  Widget _buildTabWithBadge(String title, int count) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Text(title),
        if (count > 0) ...[
          const SizedBox(width: 4),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
            decoration: BoxDecoration(
              color: Colors.red,
              borderRadius: BorderRadius.circular(10),
            ),
            constraints: const BoxConstraints(
              minWidth: 16,
              minHeight: 16,
            ),
            child: Text(
              count.toString(),
              style: const TextStyle(
                color: Colors.white,
                fontSize: 10,
                fontWeight: FontWeight.bold,
              ),
              textAlign: TextAlign.center,
            ),
          ),
        ],
      ],
    );
  }

  Widget _buildTodoList(TodoState state, List<Todo> todos) {
    if (state is TodoLoading) {
      return const Center(
        child: CircularProgressIndicator(),
      );
    }

    if (state is TodoError) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(
              Icons.error_outline,
              size: 64,
              color: Colors.red,
            ),
            const SizedBox(height: 16),
            SelectableText(
              '加载失败',
              style: Theme.of(context).textTheme.headlineSmall,
            ),
            const SizedBox(height: 8),
            SelectableText(
              state.message,
              style: Theme.of(context).textTheme.bodyMedium,
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 16),
            ElevatedButton(
              onPressed: () {
                ref.read(todoStateProvider.notifier).loadTodos();
              },
              child: const SelectableText('重试'),
            ),
          ],
        ),
      );
    }

    if (todos.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(
              Icons.assignment,
              size: 64,
              color: Colors.grey,
            ),
            const SizedBox(height: 16),
            SelectableText(
              '暂无任务',
              style: Theme.of(context).textTheme.headlineSmall,
            ),
            const SizedBox(height: 8),
            const SelectableText(
              '点击右上角“+”号创建新任务',
              style: TextStyle(color: Colors.grey),
            ),
          ],
        ),
      );
    }

    return RefreshIndicator(
      onRefresh: () async {
        ref.read(todoStateProvider.notifier).loadTodos();
      },
      child: LayoutBuilder(
        builder: (context, constraints) {
          // 使用响应式网格布局
          return _buildResponsiveGrid(todos);
        },
      ),
    );
  }

  Widget _buildResponsiveGrid(List<Todo> todos) {
    return ResponsiveGrid(
      spacing: 16,
      runSpacing: 16,
      children: todos.map((todo) => _buildTodoCard(todo)).toList(),
    );
  }

  Widget _buildTodoCard(Todo todo) {
    return AdaptiveCard(
      onTap: () {
        _showTodoDetailDialog(context, todo);
      },
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 任务标题和优先级
          Row(
            children: [
              Expanded(
                child: Text(
                  todo.title,
                  style: Theme.of(context).textTheme.titleMedium?.copyWith(
                        fontWeight: FontWeight.bold,
                        decoration: todo.status == TodoStatus.done
                            ? TextDecoration.lineThrough
                            : null,
                      ),
                  overflow: TextOverflow.ellipsis,
                  maxLines: 1,
                ),
              ),
              _buildPriorityChip(todo.priority),
            ],
          ),
          const SizedBox(height: 8),

          // 任务描述
          if (todo.description != null)
            Text(
              todo.description!,
              style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                    color: Colors.grey[600],
                  ),
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
            ),
          const SizedBox(height: 12),

          // 任务信息
          Row(
            children: [
              _buildInfoChip(
                Icons.folder,
                todo.projectName,
                Colors.blue,
              ),
              const SizedBox(width: 8),
              _buildInfoChip(
                Icons.category,
                todo.todoType.description,
                Colors.green,
              ),
              const SizedBox(width: 8),
              if (todo.assigneeName != null)
                _buildInfoChip(
                  Icons.person,
                  todo.assigneeName!,
                  Colors.orange,
                ),
            ],
          ),
          const SizedBox(height: 8),

          // 截止日期和操作按钮
          Row(
            children: [
              if (todo.dueDate != null) ...[
                Icon(
                  Icons.schedule,
                  size: 16,
                  color: todo.isNearDeadline ? Colors.red : Colors.grey,
                ),
                const SizedBox(width: 4),
                Text(
                  _formatDate(todo.dueDate!),
                  style: TextStyle(
                    fontSize: 12,
                    color: todo.isNearDeadline ? Colors.red : Colors.grey,
                  ),
                ),
              ],
              const Spacer(),
              if (todo.status != TodoStatus.done)
                _buildStatusActionButtons(todo),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildPriorityChip(Priority priority) {
    Color color;
    switch (priority) {
      case Priority.high:
        color = Colors.red;
        break;
      case Priority.medium:
        color = Colors.orange;
        break;
      case Priority.low:
        color = Colors.green;
        break;
    }

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: color.withValues(alpha: 0.1),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: color.withValues(alpha: 0.3)),
      ),
      child: SelectableText(
        priority.description,
        style: TextStyle(
          color: color,
          fontSize: 12,
          fontWeight: FontWeight.w500,
        ),
      ),
    );
  }

  Widget _buildInfoChip(IconData icon, String text, Color color) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: color.withValues(alpha: 0.1),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(
            icon,
            size: 14,
            color: color,
          ),
          const SizedBox(width: 4),
          SelectableText(
            text,
            style: TextStyle(
              color: color,
              fontSize: 12,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildActionButton(String text, Color color, VoidCallback onPressed) {
    return InkWell(
      onTap: onPressed,
      borderRadius: BorderRadius.circular(16),
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
        decoration: BoxDecoration(
          color: color.withValues(alpha: 0.1),
          borderRadius: BorderRadius.circular(16),
          border: Border.all(color: color.withValues(alpha: 0.3)),
        ),
        child: SelectableText(
          text,
          style: TextStyle(
            color: color,
            fontSize: 12,
            fontWeight: FontWeight.w500,
          ),
        ),
      ),
    );
  }

  Widget _buildStatusActionButtons(Todo todo) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        if (todo.status == TodoStatus.todo)
          _buildActionButton(
            '开始',
            Colors.blue,
            () => _updateTodoStatus(todo, TodoStatus.inProgress),
          ),
        if (todo.status == TodoStatus.inProgress) ...[
          _buildActionButton(
            '完成',
            Colors.green,
            () => _updateTodoStatus(todo, TodoStatus.done),
          ),
          const SizedBox(width: 4),
          _buildActionButton(
            '阻塞',
            Colors.red,
            () => _updateTodoStatus(todo, TodoStatus.blocked),
          ),
        ],
        if (todo.status == TodoStatus.blocked)
          _buildActionButton(
            '继续',
            Colors.blue,
            () => _updateTodoStatus(todo, TodoStatus.inProgress),
          ),
      ],
    );
  }

  String _formatDate(DateTime date) {
    final now = DateTime.now();
    final difference = date.difference(now).inDays;

    if (difference == 0) {
      return '今天';
    } else if (difference == 1) {
      return '明天';
    } else if (difference > 0) {
      return '$difference天后';
    } else {
      return '已过期${difference.abs()}天';
    }
  }

  void _updateTodoStatus(Todo todo, TodoStatus newStatus) {
    ref.read(todoStateProvider.notifier).updateTodoStatus(todo.id, newStatus);

    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: SelectableText('任务状态已更新为“${newStatus.description}”'),
        duration: const Duration(seconds: 2),
      ),
    );
  }

  void _showCreateTodoDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const SelectableText('创建任务'),
        content: const SelectableText('创建任务功能开发中...'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const SelectableText('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.of(context).pop();
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(content: SelectableText('创建任务功能开发中...')),
              );
            },
            child: const SelectableText('确定'),
          ),
        ],
      ),
    );
  }

  void _showTodoDetailDialog(BuildContext context, Todo todo) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: SelectableText(todo.title),
        content: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [
              SelectableText('项目：${todo.projectName}'),
              const SizedBox(height: 8),
              SelectableText('状态：${todo.status.description}'),
              const SizedBox(height: 8),
              SelectableText('优先级：${todo.priority.description}'),
              const SizedBox(height: 8),
              SelectableText('类型：${todo.todoType.description}'),
              if (todo.assigneeName != null) ...[
                const SizedBox(height: 8),
                SelectableText('负责人：${todo.assigneeName}'),
              ],
              if (todo.description != null) ...[
                const SizedBox(height: 12),
                const SelectableText('描述：',
                    style: TextStyle(fontWeight: FontWeight.bold)),
                const SizedBox(height: 4),
                SelectableText(todo.description!),
              ],
            ],
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const SelectableText('关闭'),
          ),
        ],
      ),
    );
  }
}
